import { useState, useRef, useEffect, Fragment, useMemo, createRef, useImperativeHandle } from 'react';
import { useDispatch, useSelector } from 'umi';
import { SecondHeaderC, ThreeHeaderC, SceneCardC } from '@/src/components';
import styles from './index.less';
import { namespace } from '@/src/newModels/pressureReport/SceneTemplateSettingsM';
import { sceneToRisk } from '../constantConfig';
import AddTableC from './addTableC';
import { formatFactorList } from './sceneDetailC';
// 风险因子根部的树 用于配置风险因子页面 标题顺序展示
const riskTree = [
  {
    title: '资产端',
    children: [
      {
        title: '市场风险因子',
        path: '资产端-市场风险因子',
      },
      {
        title: '信用风险因子',
        path: '资产端-信用风险因子',
      },
      {
        title: '流动性风险因子',
        path: '资产端-流动性风险因子',
      },
    ],
  },
  {
    title: '负债端',
    children: [
      {
        title: '投资者赎回比例',
        path: '负债端-投资者赎回比例',
      },
      {
        title: '净赎回率',
        path: '负债端-净赎回率',
      },
    ],
  },
];
const StepThree = (props) => {
  // 暴露方法给父组件
  useImperativeHandle(props.onRef, () => ({
    submit,
  }));
  const dispatch = useDispatch();
  const modelState = useSelector((state) => state[namespace]);
  const [riskList, setRiskList] = useState(riskTree); // 因子的对应标题 即第一标题 第二标题的显示
  const { stepTwoState = {} } = modelState;
  const { sceneIdInfo = [] } = stepTwoState;
  const [riskFactorList, setRiskFactorList] = useState([]); /// / 存储选中的情景项对应的因子
  // 对象函数去重
  const noRepeat = (data = []) => {
    const stringList = data.map((item) => JSON.stringify(item));
    const tempArr = Array.from(new Set(stringList));
    const resData = tempArr.map((item) => JSON.parse(item));
    return resData;
  };
  // 用于存储子表的对象
  const childRefObj = useRef({});

  // 监测选中情景项 进行因子变更操作
  useEffect(() => {
    let tempArr = [];
    if (!sceneIdInfo?.length) return;
    sceneIdInfo.map((sceneId) => {
      sceneToRisk.map((item) => {
        if (item.sceneId === sceneId) {
          tempArr = tempArr.concat(tempArr, item.riskFactor);
        }
      });
    });
    // 编辑详情进入的
    if (modelState.operateType === 'EDIT') {
      const detailInfo = modelState.mainState.sceneTemplateInfo;
      if (detailInfo && !detailInfo.oldFlag) {
        console.log('edit......');
        const { riskFactor } = detailInfo;
        const detailData = [];
        tempArr.map((factor) => {
          // eslint-disable-next-line max-nested-callbacks
          riskFactor.map((riskObj) => {
            if (factor.id === riskObj.id) {
              factor.tableData = formatFactorList(riskObj.setting.body);
              factor.tableData.forEach((x) => (x.isEdit = false));
              detailData.push({
                id: factor.id,
                itemData: factor.tableData,
              });
            }
          });
        });
        detailInfo.oldFlag = true;
        // 存储数据
        dispatch({
          type: `${namespace}/save`,
          payload: {
            tableOldData: detailData,
            mainState: {
              sceneTemplateInfo: detailInfo,
            },
          },
        });
      }
    }
    // 情景项变更 原设置因子不变， 以所选情景项 增删
    const { tableOldData } = modelState;
    if (tableOldData?.length) {
      console.log('情景项目变更了');
      tempArr.map((factor) => {
        // eslint-disable-next-line max-nested-callbacks
        tableOldData.map((tableObj) => {
          if (factor.id === tableObj.id) {
            factor.tableData = tableObj.itemData;
          }
        });
      });
    }
    const factorList = noRepeat(_.cloneDeep(tempArr));
    setRiskFactorList(factorList); // 拿到选中的因子
    // 以对象的形式 存储子组件的ref
    factorList.map((item) => {
      if (!childRefObj.current[item.id]) childRefObj.current[item.id] = createRef();
    });
    const pathList = factorList.map((item) => item.path); // 得到所有因子的路径
    const tempPath = Array.from(new Set(pathList)).join(',');
    // 拿到展示标题列表
    riskList.map((tree) => {
      if (tempPath.indexOf(tree.title) > -1) {
        tree.show = true;
      } else {
        tree.show = false;
      }
      tree.children.map((child) => {
        if (tempPath.indexOf(child.path) > -1) {
          child.show = true;
        } else {
          child.show = false;
        }
      });
    });
    setRiskList(riskList); // 得到展示标题
  }, [sceneIdInfo]);
  // 点击新增按钮 处理
  const onClickAdd = (id) => {
    childRefObj.current[id]?.current.addRow();
  };
  const submit = async () => {
    await getSubmitData();
  };
  // 点击上一步 下一步时调用
  const getSubmitData = async () => {
    const tableData = []; // 存放风险因子所有数据
    const tableOldData = []; // 存储 一份表格因子数据
    for (const key in childRefObj.current) {
      if (Object.hasOwnProperty.call(childRefObj.current, key)) {
        const element = childRefObj.current[key];
        if (element.current) {
          // 每个因子的表格
          const itemTableData = await element.current.submit();
          tableData.push({
            id: element.current.id,
            setting: {
              header: { dimension: [...element.current.attrs], threshold: ['risk1', 'risk2', 'risk3'] },
              body: formatDatas(_.cloneDeep(itemTableData)),
            },
          });
          tableOldData.push({
            id: element.current.id,
            itemData: [...itemTableData],
          });
        }
      }
    }
    console.log(tableData, '风险因子缓存数据');
    // 存储 风险因子的数据
    dispatch({
      type: `${namespace}/save`,
      payload: {
        stepThreeState: tableData,
      },
    });
    // 存储 一份表格因子数据 方便回填用
    dispatch({
      type: `${namespace}/save`,
      payload: {
        tableOldData,
      },
    });
  };
  // 格式化表格数据，
  const formatDatas = (data) => {
    const bigArr = [];
    data.forEach((obj) => {
      const arr = [];
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          if (!['isAdd', 'isEdit', 'key', 'tag'].includes(key)) {
            arr.push({
              key,
              value: obj[key],
              tag: obj.tag, // 这里处理不对  应该是单独处理根据attr
            });
          }
        }
      }
      bigArr.push(arr);
    });
    return bigArr || [];
  };
  return (
    <div className={styles.StepThree}>
      {riskList?.map((item, key) => {
        if (!item.show) return null;
        return (
          <Fragment key={key}>
            <SecondHeaderC title={item.title} />
            {item.children?.map((child, key0) => {
              if (!child.show) return null;
              return (
                <Fragment key={key0}>
                  <ThreeHeaderC title={child.title} />
                  {riskFactorList.map((factor) => {
                    if (factor.path === child.path) {
                      return (
                        <div key={factor.id} style={{ marginBottom: '15px' }}>
                          <SceneCardC
                            title={factor.name}
                            tooltip={factor.remark ? <div style={{ maxWidth: '200px' }}>{factor.remark}</div> : ''}
                            id={factor.id}
                            showAdd={true}
                            onClickAdd={onClickAdd}
                            initOpen={false}
                            content={<AddTableC onRef={childRefObj.current[factor.id]} tableData={factor.tableData} id={factor.id} />}
                          />
                        </div>
                      );
                    }
                    return null;
                  })}
                </Fragment>
              );
            })}
          </Fragment>
        );
      })}
    </div>
  );
};
export default StepThree;
